package com.hontech.bv.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.core.widget.doAfterTextChanged
import androidx.core.widget.doOnTextChanged
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hontech.bv.R
import com.hontech.bv.conn.SerialPortMod
import com.hontech.bv.conn.serial.SerialType
import com.hontech.bv.conn.serial.Uint16
import com.hontech.bv.conn.serial.Uint32
import com.hontech.bv.conn.serial.Uint8
import com.hontech.bv.task.onClick
import com.hontech.bv.ui.window.showErr
import com.hontech.bv.ui.window.showProg
import com.hontech.bv.utils.SERIAL_PORT_NAMES
import com.hontech.bv.utils.log
import com.jaredrummler.materialspinner.MaterialSpinner

class DebugActivity : AutoHideKeyActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_debug)
        Controller(this)
    }
}

private class ArgInfo (var typeIndex: Int = 0, var text: String = "0") {

    fun value(): SerialType {
        return when (typeIndex) {
            0 -> Uint8(text.toInt())
            1 -> Uint16(text.toInt())
            2 -> Uint32(text.toInt())
            else -> throw IllegalStateException("未知类型")
        }
    }
}

private class ArgItemView(view: View) : RecyclerView.ViewHolder(view) {

    companion object {
        val ARG_TYPES = listOf("UInt8", "UInt16", "UInt32")
    }

    private val spType = view.findViewById<MaterialSpinner>(R.id.id_item_arg_sp_type)
    private val etInput = view.findViewById<EditText>(R.id.id_item_arg_input)

    val btnDel = view.findViewById<Button>(R.id.id_item_arg_btn_del)

    private var innerInfo = ArgInfo()

    init {
        spType.setItems(ARG_TYPES)

        etInput.doOnTextChanged { _, _, _, _ ->
            innerInfo.text = etInput.text.toString()
        }

        spType.setOnItemSelectedListener {
                _, position, _, _ ->
            innerInfo.typeIndex = position
        }
    }

    fun setUp(info: ArgInfo) {
        innerInfo = info
        spType.selectedIndex = info.typeIndex
        etInput.setText(info.text)
    }
}

private class Controller(activity: AppCompatActivity) : RecyclerView.Adapter<ArgItemView>() {

    private val spPort = activity.findViewById<MaterialSpinner>(R.id.id_debug_spinner)
    private val btnOpen = activity.findViewById<Button>(R.id.id_debug_btn_open_port)
    private val btnClear = activity.findViewById<Button>(R.id.id_debug_btn_arg_clear)
    private val btnAdd = activity.findViewById<Button>(R.id.id_debug_btn_arg_add)
    private val btnSend = activity.findViewById<Button>(R.id.id_debug_btn_send)
    private val rvArg = activity.findViewById<RecyclerView>(R.id.id_debug_rv_arg)
    private val etReq = activity.findViewById<EditText>(R.id.id_debug_et_req)
    private val etDest = activity.findViewById<EditText>(R.id.id_debug_et_dest)
    private val args = ArrayList<ArgInfo>()

    init {
        spPort.setItems(SERIAL_PORT_NAMES)
        btnOpen.onClick(::onClickOpen)

        rvArg.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        rvArg.adapter = this
        btnClear.setOnClickListener {
            args.clear()
            notifyDataSetChanged()
        }
        btnAdd.setOnClickListener {
            args.add(ArgInfo())
            notifyDataSetChanged()
        }
        btnSend.onClick(::onClickSend)
    }

    private fun req(): Int {
        val text = etReq.text.toString()
        return text.toInt(16)
    }

    private fun dest(): Int {
        return etDest.text.toString().toInt()
    }

    private fun arg(): Array<SerialType> {
        val ts = Array(args.size) { args[it].value() }
        return ts
    }

    private suspend fun onClickSend() {
        val prog = showProg("发送数据", "")
        try {
            val req = req()
            val dest = dest()
            SerialPortMod.request(req, dest, arg()).assert("测试")
            prog.success("成功返回")
        } catch (e: Exception) {
            e.printStackTrace()
            prog.error(e)
        }
    }

    private suspend fun onClickOpen() {
        if (SerialPortMod.isOpen()) {
            SerialPortMod.close()
            btnOpen.text = "打开"
            return
        }
        try {
            SerialPortMod.open( SERIAL_PORT_NAMES[spPort.selectedIndex] )
            btnOpen.text = "关闭"
        } catch (e: Exception) {
            e.printStackTrace()
            showErr("打开失败", e)
        }
    }

    override fun onBindViewHolder(holder: ArgItemView, position: Int) {
        holder.setUp(args[position])
        holder.btnDel.setOnClickListener {
            args.removeAt(position)
            notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArgItemView {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_arg, parent, false)
        return ArgItemView(view)
    }

    override fun getItemCount(): Int {
        return args.size
    }
}



